﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestRecordDisting
{
    static class Program
    {
        static object _lockObj = new object();
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);  
            ////处理UI线程异常  
            //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);  
            ////处理非UI线程异常  
            //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);  
            
            //TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            //TODO
            SaveException("系统Task错误", e.Exception);
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            SaveException("系统线程错误", e.Exception);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            SaveException("系统未处理错误", e.ExceptionObject as Exception);
        }

        static void SaveException(string title, Exception e)
        {
            lock (_lockObj)
            {
                string msg = string.Format("{0}------{1}\r\n{2}", DateTime.Now.ToString(), title, e.ToString());
                try
                {
                    using (StreamWriter sw = new StreamWriter(@"ErrLog.txt", true))
                    {
                        sw.WriteLine(msg);
                        sw.WriteLine("------------------------------------------------------------------------");
                        sw.Close();
                    }
                }
                catch { }
            }
        }
    }
}
